
package main

import (
"fmt"
"sync"
"sync/atomic"
"time"

"github.com/panjf2000/ants/v2"
)

var sum int32

func myFunc(i interface{}) {
	n := i.(int32)
	atomic.AddInt32(&sum, n)
	//fmt.Printf("run with %d\n", n)
}

func demoFunc() {
	time.Sleep(10 * time.Millisecond)
	//fmt.Println("Hello World!")
}

func main() {
	defer ants.Release()	// 预关闭

	runTimes := 10000

	// 使用池
	var wg sync.WaitGroup
	syncCalculateSum := func() {
		// 打印"Hello World!"
		demoFunc()
		wg.Done()
	}
	// 循环1000
	for i := 0; i < runTimes; i++ {
		wg.Add(1)
		// 提交会话到 pool
		_ = ants.Submit(syncCalculateSum)
	}
	wg.Wait()
	// ants.Running() 返回当前正在运行的goroutine数。
	fmt.Printf("running goroutines: %d\n", ants.Running())
	fmt.Printf("finish all tasks.\n")

	// Use the pool with a method,
	// 将goroutine池的容量设置为10，过期时间设置为1秒。
	p, _ := ants.NewPoolWithFunc(10, func(i interface{}) {
		myFunc(i)
		wg.Done()
	})
	defer p.Release()
	// Submit tasks one by one.
	for i := 0; i < runTimes; i++ {
		wg.Add(1)
		_ = p.Invoke(int32(i))
	}
	wg.Wait()
	fmt.Printf("running goroutines: %d\n", p.Running())
	fmt.Printf("finish all tasks, result is %d\n", sum)
	//if sum != 499500 {
	//	panic("the final result is wrong!!!")
	//}
}
